package com.batdream.message.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class SpringContextUtils implements ApplicationListener<ContextRefreshedEvent>  {

    private static ApplicationContext context;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        SpringContextUtils.context = contextRefreshedEvent.getApplicationContext();
    }

    public static ApplicationContext getContext(){
        return context;
    }

    /**
     * 根据bean的id来查找对象
     */
    public static Object getBeanById(String id){
        return context.getBean(id);
    }

    /**
     * 根据bean的class来查找对象
     */
    public static Object getBeanByClass(Class c){
        return context.getBean(c);
    }

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     */
    public static Map getBeansByClass(Class c){
        return context.getBeansOfType(c);
    }


}
